<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>防抖节流</title>
  </head>
  <body>
    <input type="text" id="input" />
  </body>
  <script>
    let validate = debounce(() => {
      console.log("haha");
    }, 1200);
    document.querySelector("#input").addEventListener("input", validate);
    function debounce(func, wait, immediate) {
      let timeout;
      return function () {
        let context = this;
        let args = arguments;

        if (timeout) clearTimeout(timeout);
        if (immediate) {
          var callNow = !timeout;
          timeout = setTimeout(() => {
            timeout = null;
          }, wait);
          if (callNow) func.apply(context, args);
        } else {
          timeout = setTimeout(function () {
            func.apply(context, args);
          }, wait);
        }
      };
    }
  </script>
</html>
